<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper"
         v-loading='isLoading'>
      <main class="aui-content login-content"
            :style="scale">
        <div class="login-body">
          <h3 class="login-title">忘记密码</h3>
          <el-form :model="dataForm"
                   :rules="dataRule"
                   ref="dataForm"
                   @keyup.enter.native="dataFormSubmitHandle()">
            <el-form-item prop="number">
              <el-input v-model.trim="dataForm.number"
                        :readonly="isReadonly"
                        :maxlength='12'
                        placeholder="手机号">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-user"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model.trim="dataForm.code"
                            :readonly="isReadonly"
                            @select="selectInput"
                            :maxlength='6'
                            :placeholder="$t('registered.code')">
                  </el-input>
                </el-col>
                <el-col :span="10"
                        class="login-captcha">
                  <el-button type="text"
                             @click="getCode">{{num>0 ? `${num}秒后重新获取`:'获取验证码' }}</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item prop="passwd">
              <el-input v-model.trim="dataForm.passwd"
                        :readonly="isReadonly"
                        type="password"
                        show-password
                        :placeholder="$t('registered.password')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-lock"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="confirm">
              <el-input v-model.trim="dataForm.confirm"
                        :readonly="isReadonly"
                        type="password"
                        show-password
                        :placeholder="$t('registered.confirm')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-lock"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="dataFormSubmitHandle"
                         class="w-percent-100">提交</el-button>
            </el-form-item>
            <el-form-item>
              <router-link to="login">
                <el-button type="success"
                           class="w-percent-100">返回登录</el-button>
              </router-link>
            </el-form-item>
          </el-form>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import base64 from '@/utils/base64'
// import Qs from 'qs'
import { isMobile } from '@/utils/validate'
export default {
  data () {
    let password = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length > 16) {
        callback(new Error('请输入8-16位,包括大写字母,小写字母,数字'))
      } else {
        let pPattern = /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{8,16}/
        // let order = 0 // 顺序
        if (pPattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入8-16位,包括大写字母,小写字母,数字'))
        }
      }
    }
    return {
      scale: {
        transform: `scale(1)`
      },
      isReadonly: true,
      isLoading: false,
      i18nMessages: messages,
      captchaPath: '',
      num: 0,
      dialogVisible: false,
      dataForm: {
        type: 2,
        passwd: '',
        number: '',
        code: '',
        confirm: ''
      },
      dataRule: {
        passwd: [
          { required: true, validator: password, trigger: 'change' }
        ],
        confirm: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        number: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    let self = this
    let width = document.documentElement.offsetWidth
    let num = width * 0.0005208
    if (num > 1) {
      num = 1
    }
    self.scale = {
      transform: `scale(${num})`
    }
    setTimeout(() => {
      this.isReadonly = false
    }, 500)
  },
  methods: {
    /**
     * 获取验证码
     */
    getCode () {
      let time = base64.decode(window.localStorage.getItem('time')) || null
      let nowTime = new Date().getTime()
      if (!isMobile(this.dataForm.number)) {
        this.$message.error('请填写正确的手机号')
        return
      }
      if (nowTime - time > 60000) {
        let tempNum = 60
        window.localStorage.setItem('time', base64.encode(nowTime.toString()))
        window.localStorage.setItem('num', base64.encode(tempNum.toString() + this.str))
        this.isLoading = true
        // 获取验证码
        this.$http.get(`/getSmsCode?phone=${this.dataForm.number}`).then(({ data: res }) => {
          this.isLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success('验证码已发出，请注意接收')
        }).catch(() => {
          this.isLoading = false
        })
        // eslint-disable-next-line new-cap
        this.timer = setInterval(() => {
          let num = base64.decode(window.localStorage.getItem('num'))
          num = num.replace(this.str, '')
          num--
          this.num = num
          window.localStorage.setItem('num', base64.encode(num.toString() + this.str))
          if (num <= 0) {
            window.clearInterval(this.timer)
          }
        }, 1000)
      }
    },
    selectInput () {
    },
    /**
     * 表单提交
     */
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // 验证两次输入密码是否一样
        if (this.dataForm.passwd !== this.dataForm.confirm) {
          this.$message.error('两次的密码不一致')
          return false
        }
        delete this.dataForm.confirm
        this.isLoading = true
        // 重新修改密码
        this.$http.put('/forgetPassword', {
          phone: this.dataForm.number,
          code: this.dataForm.code,
          password: this.dataForm.passwd,
          ackPassword: this.dataForm.passwd
        }).then(({ data: res }) => {
          this.isLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$router.replace({ name: 'login' })
            }
          })
        }).catch(() => {
          this.isLoading = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss">
.login-header {
  img {
    width: 300px;
  }
}
</style>
